import re

from django.contrib.auth import logout
from django.shortcuts import render
from django.shortcuts import redirect
from django.conf import settings
from . import models
from . import forms
from django.core import serializers
import hashlib
# Create your views here.

import datetime


def test(request):
    """改动的代码上传到服务器"""
    print("哈哈哈哈")


# 产生哈希码
def hash_code(s, salt='mysite'):  # 加点盐
    h = hashlib.sha256()
    s += salt
    h.update(s.encode())  # update方法只接收bytes类型
    return h.hexdigest()


# 获得确认码
def make_confirm_string(user):
    now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    code = hash_code(user.name, now)
    models.ConfirmString.objects.create(code=code, user=user, )
    return code


# 发送邮件
def send_email(email, code):
    from django.core.mail import EmailMultiAlternatives

    subject = '来自张嘉诚的注册确认邮件'

    text_content = '''感谢注册\
                    如果你看到这条消息，说明你的邮箱服务器不提供HTML链接功能，请联系管理员！'''

    html_content = '''
                    <p>感谢注册<a href="http://{}/confirm/?code={}" target=blank>员工健康打卡系统</a></p>
                    <p>请点击站点链接完成注册确认！</p>
                    <p>此链接有效期为{}天！</p>
                    '''.format('112.124.18.209', code, settings.CONFIRM_DAYS)

    msg = EmailMultiAlternatives(subject, text_content, settings.EMAIL_HOST_USER, [email])
    msg.attach_alternative(html_content, "text/html")
    msg.send()


def index(request):
    if not request.session.get('is_login', None):
        return redirect('/login/')
    # return render(request, 'login/index.html')
    # 如果用户成功登录的话，重定向到视图函数 menu
    return redirect("/menu")


def menu(request):
    # 用户没有登录不能进入
    if not request.session.get('is_login', None):
        return redirect("/login")

    return render(request, 'login/menu.html')


def login(request):
    if request.session.get('is_login', None):  # 不允许重复登录
        return redirect('/menu/')
    if request.method == 'POST':
        login_form = forms.UserForm(request.POST)
        message = '请检查填写的内容！'
        if login_form.is_valid():
            username = login_form.cleaned_data.get('username')
            password = login_form.cleaned_data.get('password')

            try:
                user = models.User.objects.get(name=username)
            except:
                message = '用户不存在！'
                return render(request, 'login/login.html', locals())

            if not user.has_confirmed:
                message = '该用户还未经过邮件确认！'
                return render(request, 'login/login.html', locals())

            if user.password == hash_code(password):
                request.session['is_login'] = True
                request.session['user_id'] = user.id
                request.session['user_name'] = user.name
                serialized_user = serializers.serialize("json", [user])
                request.session['user'] = serialized_user
                return redirect('/menu/')
            else:
                message = '密码不正确！'
                return render(request, 'login/login.html', locals())
        else:
            return render(request, 'login/login.html', locals())

    login_form = forms.UserForm()
    return render(request, 'login/login.html', locals())


def register(request):
    if request.session.get('is_login', None):
        return redirect('/index/')

    if request.method == 'POST':
        register_form = forms.RegisterForm(request.POST)
        message = "请检查填写的内容！"
        if register_form.is_valid():
            username = register_form.cleaned_data.get('username')
            sex = register_form.cleaned_data.get('sex')
            num = register_form.cleaned_data.get('num')
            dept = register_form.cleaned_data.get('dept')
            party = register_form.cleaned_data.get('party')
            password1 = register_form.cleaned_data.get('password1')
            password2 = register_form.cleaned_data.get('password2')
            email = register_form.cleaned_data.get('email')

            if password1 != password2:
                message = '两次输入的密码不同！'
                return render(request, 'login/register.html', locals())
            else:
                same_name_user = models.User.objects.filter(name=username)
                if same_name_user:
                    message = '用户名已经存在'
                    return render(request, 'login/register.html', locals())

                same_email_user = models.User.objects.filter(email=email)
                if same_email_user:
                    message = '该邮箱已经被注册了！'
                    return render(request, 'login/register.html', locals())

                new_user = models.User()
                new_user.name = username
                new_user.password = hash_code(password1)
                new_user.email = email
                new_user.sex = sex
                new_user.num = num
                new_user.dept = dept
                new_user.party = party
                new_user.save()

                code = make_confirm_string(new_user)
                send_email(email, code)
                message = '请前往邮箱进行确认！'

                return render(request, 'login/affirm.html', locals())
        else:
            return render(request, 'login/register.html', locals())

    register_form = forms.RegisterForm()
    return render(request, 'login/register.html', locals())


def logout_view(request):
    if not request.session.get('is_login', None):
        # 如果本来就未登录，也就没有登出一说
        return redirect("/login/")
    # 可用logout(request) 因为request 封装用户登录的状态
    logout(request)
    # request.session.flush()
    # 或者使用下面的方法
    # del request.session['is_login']
    # del request.session['user_id']
    # del request.session['user_name']
    return redirect("/login/")


# 404
def page_not_found(request, exception):
    return render(request, 'login/404.html')


# 用户确认
def user_confirm(request):
    code = request.GET.get('code', None)
    message = ''
    try:
        confirm = models.ConfirmString.objects.get(code=code)
    except:
        message = '无效的确认请求!'
        return render(request, 'login/confirm.html', locals())

    c_time = confirm.c_time
    now = datetime.datetime.now()
    if now > c_time + datetime.timedelta(settings.CONFIRM_DAYS):
        confirm.user.delete()
        message = '您的邮件已经过期！请重新注册!'
        return render(request, 'login/confirm.html', locals())
    else:
        confirm.user.has_confirmed = True
        confirm.user.save()
        confirm.delete()
        message = '感谢确认，请使用账户登录！'
        return render(request, 'login/confirm.html', locals())

# def image_code_view(request):
#     """
#     生成图形验证码
#     url: /image_code/
#     :param request:
#     :return:
#     """
#     # 1. 生成验证码  随机生成字符串, 生成图片(二进制)
#     text, image = captcha.generate_captcha()
#
#     # 2. 在后端保存图形验证码 (保存在 session中, 并设置过期时间) 方便用户填写手机时校验
#     request.session['image_code'] = text
#     request.session.set_expiry(constants.IMAGE_CODE_EXPIRES)  # 设置过期时间为300秒
#
#     # 3. 记录一个日志--- 本项目没有log日志，因此不用记录
#     # logger.info('Image code:{}'.format(text))
#
#     # 4. 返回图形验证码和图片(图片为二进制, 写上返回内容的类型content_type)
#     return HttpResponse(content=image, content_type='image/jpg')
